package com.zmx.doctor.view.activity;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.doctor.BaseActivity;
import com.zmx.doctor.R;
import com.zmx.doctor.adapter.CategoryAdapter;
import com.zmx.doctor.adapter.GoodsItemAdapter;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.DrugClassification;
import com.zmx.doctor.pojo.Goods;
import com.zmx.doctor.pojo.GoodsOrder;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 时间：2020/7/18 15:36
 * 功能：
 */
public class PrescribingActivity extends BaseActivity implements GoodsItemAdapter.goodsItemListener {

    @BindView(R.id.rv_rvliandong_Left)
    RecyclerView rv_rvliandong_Left;
    @BindView(R.id.rv_rvliandong_Right)
    RecyclerView rv_rvliandong_Right;
    @BindView(R.id.button)
    Button button;
    @BindView(R.id.text_number)
    TextView textNumber;
    @BindView(R.id.search_btn)
    RelativeLayout search_btn;
    @BindView(R.id.text_total)
    TextView textTotal;
    @BindView(R.id.z_goods)
    TextView z_goods;

    private Integer logo,type;
    private String ask_id,p_id,z_type,temp_id;

    private CategoryAdapter category_adapter;
    private List<DrugClassification> dcfs;

    private GoodsItemAdapter goodsItemAdapter;
    private List<Goods> goods;

    private List<GoodsOrder> goods_car;


    private int total_numbre=0;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_prescribing;
    }

    @Override
    protected void initViews() {


        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);

        logo = Integer.parseInt(getIntent().getStringExtra("logo"));
        type = Integer.parseInt(getIntent().getStringExtra("type"));
        z_type = this.getIntent().getStringExtra("z_type");
        temp_id = this.getIntent().getStringExtra("temp_id");

        if (logo == 1){

            ask_id = getIntent().getStringExtra("ask_id");
            p_id = getIntent().getStringExtra("p_id");

        }


        dcfs = new ArrayList<>();
        goods_car = new ArrayList<>();
        rv_rvliandong_Left.setLayoutManager(new LinearLayoutManager(mActivity));
        category_adapter = new CategoryAdapter(mActivity);
        rv_rvliandong_Left.setAdapter(category_adapter);
        category_adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                category_adapter.mCheckedPosition = listPosition;
                category_adapter.notifyDataSetChanged();
                getGoods(dcfs.get(listPosition).getId());

            }
        });

        rv_rvliandong_Right.setLayoutManager(new LinearLayoutManager(mActivity));
        goodsItemAdapter = new GoodsItemAdapter(mActivity);
        goodsItemAdapter.setGoodsItemListeners(this);
        goods = new ArrayList<>();
        rv_rvliandong_Right.setAdapter(goodsItemAdapter);

        getGroup();
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray array = object.getJSONArray("data");
                        Gson gson = new Gson();
                        for (int i = 0; i < array.length(); i++) {

                            DrugClassification dcf = gson.fromJson(array.getJSONObject(i).toString(), DrugClassification.class);
                            dcfs.add(dcf);

                        }
                        category_adapter.setListAndNotifyDataSetChanged(dcfs);//就是设置list然后刷新

                        if (dcfs.size() > 0) {

                            getGoods(dcfs.get(0).getId());

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;

                case 2:

                    goods.clear();
                    goodsItemAdapter.notifyDataSetChanged();
                    Log.e("数据", "数据" + msg.obj.toString());
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONArray array = object.getJSONArray("data");
                        Gson gson = new Gson();
                        for (int i = 0; i < array.length(); i++) {

                            Goods g = gson.fromJson(array.getJSONObject(i).toString(), Goods.class);
                            goods.add(g);

                        }
                        goodsItemAdapter.setListAndNotifyDataSetChanged(goods);//就是设置list然后刷新

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 3:

                    Log.e("fdaf", "发生的发生" + msg.obj.toString());

                    break;

            }

        }
    };

    public void getGroup() {

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(null)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getGroup");
        params.put("data[]", "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.make/entry", params, handler, 1, 404);

    }

    public void getGoods(int group_id) {

        List<String> l = new ArrayList<>();
        l.add(type+"");
        l.add(group_id + "");
        l.add(10 + "");
        l.add(1 + "");

        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(l)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getGoods");
        params.put("data[group_id]", group_id);
        params.put("data[classify]", type);
        params.put("data[row]", 1 + "");
        params.put("data[number]", 10 + "");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.make/entry", params, handler, 2, 404);

    }

    private Dialog modify_dialogs;//弹出框
    @RequiresApi(api = Build.VERSION_CODES.N)
    public void showPhoto(Goods g) {

        View view;//选择性别的view

        modify_dialogs = new Dialog(mActivity, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_shopping, null);
        //将布局设置给Dialog
        modify_dialogs.setContentView(view);
        //获取当前Activity所在的窗体
        Window dialogWindow = modify_dialogs.getWindow();

        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //        lp.y = 20;//设置Dialog距离底部的距离

        //// 以下这两句是为了保证按钮可以水平满屏
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        modify_dialogs.onWindowAttributesChanged(lp);
        //       将属性设置给窗体
//        modify_dialogs.setCanceledOnTouchOutside(false);
        modify_dialogs.show();//显示对话框

        TextView name = view.findViewById(R.id.name);
        name.setText("商品名称" + g.getName());
        TextView desc = view.findViewById(R.id.desc);
        desc.setText("药品描述：" + Html.fromHtml((g.getDescribe()), 10));
        EditText y_number = view.findViewById(R.id.y_number);
        EditText y_sm = view.findViewById(R.id.y_sm);
        EditText e_day = view.findViewById(R.id.e_day);

        TextView regular = view.findViewById(R.id.regular);
        regular.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String[] items = {"片/次", "瓶/次", "剂/次"};
                showNotice(regular,items);
            }
        });
        TextView e_rate = view.findViewById(R.id.e_rate);
        e_rate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String[] items = {"每日一次", "每日二次", "每日三次"};
                showNotice(e_rate,items);
            }
        });
        TextView e_usage = view.findViewById(R.id.e_usage);
        e_usage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String[] items = {"口服", "外用", "注射"};
                showNotice(e_usage,items);
            }
        });

        Button submit = view.findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (y_number.getText().toString().equals("")){

                    Toast("数量不能为空！");
                    return;

                }

                if (y_sm.getText().toString().equals("")){

                    Toast("使用说明不能为空！");
                    return;

                }
                if (e_day.getText().toString().equals("")){

                    Toast("用药时长不能为空！");
                    return;

                }

                int t_number = 0;
                double money = 0;

                GoodsOrder go = new GoodsOrder();
                go.setGoods_id(g.getGoods_id());
                go.setGoods_name(g.getName());
                go.setPrice(g.getPrice());
                go.setNumber(Integer.parseInt(y_number.getText().toString()));
                go.setUsage(e_usage.getText().toString());
                go.setDescribe(g.getDescribe());
                go.setRate(e_rate.getText().toString());
                go.setEvery(y_number.getText().toString()+regular.getText().toString());
                go.setDescribes(y_sm.getText().toString());
                go.setSpecs(y_number.getText().toString()+regular.getText().toString());
                go.setDay(e_day.getText().toString());
                go.setType(0);
                goods_car.add(go);

                for (GoodsOrder goodsOrder:goods_car){
                    t_number = t_number+goodsOrder.getNumber();

                    money = money+goodsOrder.getNumber()*goodsOrder.getPrice();
                }

                total_numbre = t_number;

                textTotal.setText(money+"");
                textNumber.setText("已选择"+total_numbre+"种药品");

                modify_dialogs.dismiss();

            }
        });

    }

    public void showPhoto() {

        View view;//选择性别的view

        modify_dialogs = new Dialog(mActivity, R.style.ActionSheetDialogStyle);
        //填充对话框的布局
        view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_goods, null);
        //将布局设置给Dialog
        modify_dialogs.setContentView(view);
        //获取当前Activity所在的窗体
        Window dialogWindow = modify_dialogs.getWindow();

        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        //        lp.y = 20;//设置Dialog距离底部的距离

        //// 以下这两句是为了保证按钮可以水平满屏
        lp.width = ViewGroup.LayoutParams.MATCH_PARENT;
        lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        // 设置显示位置
        modify_dialogs.onWindowAttributesChanged(lp);
        //       将属性设置给窗体
//        modify_dialogs.setCanceledOnTouchOutside(false);
        modify_dialogs.show();//显示对话框

        EditText e_name = view.findViewById(R.id.e_name);
        EditText e_specs = view.findViewById(R.id.e_specs);
        EditText e_every = view.findViewById(R.id.e_every);
        EditText e_day = view.findViewById(R.id.e_day);
        EditText e_describe = view.findViewById(R.id.e_describe);
        TextView regular = view.findViewById(R.id.regular);
        regular.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String[] items = {"片/次", "瓶/次", "剂/次"};
                showNotice(regular,items);
            }
        });
        TextView e_rate = view.findViewById(R.id.e_rate);
        e_rate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String[] items = {"每日一次", "每日二次", "每日三次"};
                showNotice(e_rate,items);
            }
        });
        TextView e_usage = view.findViewById(R.id.e_usage);
        e_usage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                final String[] items = {"口服", "外用", "注射"};
                showNotice(e_usage,items);
            }
        });

        Button submit = view.findViewById(R.id.submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (e_name.getText().toString().equals("")){

                    Toast("名称不能为空！");
                    return;

                }

                if (e_specs.getText().toString().equals("")){

                    Toast("规格不能为空！");
                    return;

                }
                if (e_every.getText().toString().equals("")){

                    Toast("用量不能为空！");
                    return;

                }
                if (e_day.getText().toString().equals("")){

                    Toast("用药时长不能为空！");
                    return;

                }

                GoodsOrder go = new GoodsOrder();
                go.setGoods_id(0);
                go.setGoods_name(e_name.getText().toString());
                go.setPrice(0);
                go.setNumber(Integer.parseInt(e_every.getText().toString()));
                go.setSpecs(e_specs.getText().toString());
                go.setDay(e_day.getText().toString());
                go.setDescribes(e_describe.getText().toString());
                go.setRate(e_rate.getText().toString());
                go.setUsage(e_usage.getText().toString());
                go.setType(1);
                goods_car.add(go);

                int t_number = 0;
                double money = 0;
                for (GoodsOrder goodsOrder:goods_car){
                    t_number = t_number+goodsOrder.getNumber();

                    money = money+goodsOrder.getNumber()*goodsOrder.getPrice();
                }

                total_numbre = t_number;

                textTotal.setText(money+"");
                textNumber.setText("已选择"+total_numbre+"种药品");

                Toast("自建成功");
                modify_dialogs.dismiss();
            }
        });

    }

    private AlertDialog alertDialog1; //信息框
    public void showNotice(TextView textView,String[] items) {
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(mActivity);
        alertBuilder.setTitle("请选择");
        alertBuilder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                textView.setText(items[i]);
                alertDialog1.dismiss();
            }
        });
        alertDialog1 = alertBuilder.create();
        alertDialog1.show();
    }


    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void setGoodsItemListener(Goods g) {
        showPhoto(g);
    }


    @OnClick({R.id.z_goods,R.id.button,R.id.search_btn})
    public void onViewClicked(View view) {

        switch (view.getId()){

            case R.id.button:

                if (goods_car.size()<=0){
                    Toast("没有选择药品");
                    return;
                }

                Bundle bundle = new Bundle();
                bundle.putSerializable("lists", (Serializable) goods_car);
                bundle.putString("logo",logo+"");
                bundle.putString("ask_id", ask_id);
                bundle.putString("p_id", p_id);
                bundle.putString("z_type", z_type);
                bundle.putString("temp_id", temp_id);
                startActivity(GoodsOrderDetailsActivity.class,bundle);

                break;

            case R.id.z_goods:
                showPhoto();
                break;

            case R.id.search_btn:

                Intent intent = new Intent();
                intent.setClass(mActivity, SearchDrugActivity.class);
                startActivityForResult(intent, 101);

                break;

        }

}

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (data != null) {

            switch (requestCode){  //根据请求码可处理不同活动返回的数据

                case 101: //返回的请求码

                    Bundle bundle = data.getExtras();
                    List<GoodsOrder> gos = (List<GoodsOrder>) bundle.getSerializable("goods_car");

                    if (gos != null){

                        for (GoodsOrder g:gos){

                            goods_car.add(g);

                        }

                        int t_number = 0;
                        double money = 0;
                        for (GoodsOrder goodsOrder:goods_car){
                            t_number = t_number+goodsOrder.getNumber();

                            money = money+goodsOrder.getNumber()*goodsOrder.getPrice();
                        }

                        total_numbre = t_number;

                        textTotal.setText(money+"");
                        textNumber.setText("已选择"+total_numbre+"种药品");
                    }

                    break;
            }

        }


    }


}
